﻿using MediatR;
using Sgr.Caching.Services;
using Sgr.Domain.Uow;
using Sgr.UPMS.Events;
using Sgr.UPMS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sgr.UPMS.Application;
using Sgr.UPMS.Domain.Users;

namespace Xunit.Sgr.EntityFrameworkCore
{
    public class TestUserAuthChangedDomainEventHandle : INotificationHandler<UserAuthChangedDomainEvent>
    {
        private readonly IUpmsQueryContext _upmsQueryContext;
        private readonly ICacheManager _cacheManager;

        public TestUserAuthChangedDomainEventHandle(
             IUpmsQueryContext upmsQueryContext,
             ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
            _upmsQueryContext = upmsQueryContext;
        }

        public async Task Handle(UserAuthChangedDomainEvent notification, CancellationToken cancellationToken)
        {
            var user = _upmsQueryContext.Query<User>().FirstOrDefault(x => x.Id == notification.UserId);
            if (user != null)
            {
                await _cacheManager.RemoveAsync(string.Format(CacheKeys.AUTH_ORG_USER_KEY, user.OrgId, user.Id), cancellationToken);
            }
        }
    }
}